package com.asimplefox.controllers;

import com.asimplefox.serurity.UserRoleDetails;
import com.asimplefox.service.IPaypalOrderService;
import com.asimplefox.service.abst.ResultU;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * @author github.kloping
 */
@Slf4j
@RestController
@RequestMapping("/paypalv2")
@PreAuthorize("hasAnyAuthority('user')")
public class PayPalController implements ResultU {

    @Autowired
    IPaypalOrderService paypalOrderService;

    @GetMapping("/back")
    public String back(@RequestParam("token") String token, @RequestParam("PayerID") String PayerID) throws IOException {
        return paypalOrderService.backCap(token, PayerID);
    }

    @GetMapping("/cancel")
    public String cancel(@RequestParam("token") String token) throws IOException {
        return paypalOrderService.cancel(token);
    }

    public static Map<Integer, String> priceMap = Map.of(1, "测", 10, "月", 25, "季", 90, "年");

    @GetMapping("/cap")
    public String cap(@AuthenticationPrincipal UserRoleDetails details,
                      @RequestParam("price") Integer price) throws IOException {
        return paypalOrderService.create(details, price);
    }

    @GetMapping("/query")
    public String query(@RequestParam("token") String id) {
        try {
            return paypalOrderService.query(id);
        } catch (IOException e) {
            e.printStackTrace();
            return fail("server error");
        }
    }

    @GetMapping("/list")
    public List list(@AuthenticationPrincipal UserRoleDetails details) {
        return paypalOrderService.list(details.getUser());
    }
}
